<?php
require_once('Model/DB.php');
class Model_Uploader
{
    var $cache_dir;
    
    public function __construct()
    {
        $config          = __get_config();
        $this->cache_dir = SiteManageRootDir . $config['SiteManage']['cache_dir'];
    }
    // preview (for image)
    public function preview($file)
    {
        chdir($this->cache_dir);
        if (file_exists($file)){
            $contents = file_get_contents($file);
            $info     = getimagesize($file);
            header('Content-type: '. $info['mime']);
            echo($contents);
        }
    }
    // upload -> cache
    public function getUploadInfo()
    {
        chdir($this->cache_dir);
        $info = array();
        if (isset($_FILES)){
            $key = array_shift(array_keys($_FILES));
            if(is_array($_FILES[$key])){
                
                $key = array_shift(array_keys($_FILES));
                // 階層
                $arr  = $_FILES[$key]['error'];
                $c    = 0;
                $key2 = '';
                while(is_array($arr)){
                    $keys  = array_keys($arr);
                    $key2 .= '["'. array_shift($keys) .'"]';
                    $arr   = array_shift($arr);
                }
                eval('$tmp_file = $_FILES[$key]["tmp_name"]' . $key2 . ';');
                $cache = array_pop(explode('/', $tmp_file));
                if (move_uploaded_file($tmp_file, $cache)){
                    $info          = array();
                    foreach($_FILES[$key] as $k => $_){
                        eval('$info[$k] = $_FILES[$key][$k]' . $key2 . ';'); 
                    }
                    $info['filename'] = $info["name"];//アップロードファイル名
                    $info['cache'] = $cache;
                    $info['name']  = preg_replace('/^file_/', '', $key).str_replace('[0]', '[]', str_replace('"', '', $key2));//inputタグのname
                    $info['code']  = sha1(preg_replace('/^file_/', '', $key).str_replace('[0]', '[]', str_replace('"', '', $key2)));
                }
            }
            else{
                $cache = array_pop(explode('/', $_FILES[$key]['tmp_name']));
                if (move_uploaded_file($_FILES[$key]['tmp_name'], $cache)){
                    $info          = $_FILES[$key];
                    $info['cache'] = $cache;
                    $info['code']  = sha1(preg_replace('/^file_/', '', $key));
                }
            }
        }
        return $info;
    }
    // cache -> site_dir
    public function moveCacheImage($cache, $move_to, $base_name, $serial = false)
    {
        if(!file_exists($move_to)){
            return false;
        }
        
        if ($serial == true){
            $filename = $this->getNewFilename($move_to, $base_name);
        }
        else{
            $filename = $base_name;
        }
        
       
        
        chdir($this->cache_dir);
        if(!file_exists($cache)){
        	
            return false;
        }
        
        $info      = getimagesize($cache);
        $ext       = array_pop(explode('/', $info['mime']));
        $filename .= '.' . ($ext == 'jpeg' ? 'jpg' : $ext);
        
        $path = $move_to. $filename;
       
        /*
        if(!file_exists($cache)){
            return false;
        }
        */
        copy($cache, $path);
        chmod($path, 0777);
        unlink($cache);
        
        return $filename;
    }
    public function moveCacheFile($cache, $move_to, $base_name, $serial = false)
    {
        if(!file_exists($move_to)){
            return false;
        }
        if ($serial == true){
            $filename = $this->getNewFilename($move_to, $base_name);
        }
        else{
            $filename = $base_name;
        }
        chdir($this->cache_dir);
        if(!file_exists($cache)){
            return false;
        }
        $finfo     = new finfo(FILEINFO_MIME, "/usr/share/misc/magic");
        $mime_type = $finfo->file($cache);
        $ext       = $this->getExtension($mime_type);
        $filename .= '.' . ($ext == 'jpeg' ? 'jpg' : $ext);
        
        $path = $move_to. $filename;
        copy($cache, $path);
        chmod($path, 0777);
        unlink($cache);
        
        return $filename;
    }
    private function getNewFilename($dir, $base_name)
    {
        chdir($dir);
        $seq = 1;
        if ($d = opendir('.')){
            while($file = readdir($d)){
                if(filetype($file) == 'file' && preg_match("/^{$base_name}_/", $file)){
                    $num = (int)array_pop(explode('_', array_shift(explode('.', $file))));
                    if ($num >= $seq){
                        $seq = $num + 1;
                    }
                }
            }
        }
        return $base_name . '_' . sprintf('%05d', $seq);
    }
    private function getExtension($mime_type)
    {
        $list = file('/etc/mime.types');
        foreach($list as $row){
            $row   = preg_replace('/\s+/',',',trim($row));
            $slice = explode(',', $row);
            if ($slice[0] == $mime_type){
                return $slice[1];
            }
        }
        return '';
    }
    
}
?>